package cn.bugstack.ai.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;

import java.util.*;
import java.util.concurrent.*;

/**
 * 会话管理服务
 * 管理 WebSocket 会话和聊天历史
 * 
 * @author bugstack
 */
@Slf4j
@Service
public class SessionManager {
    
    /**
     * 存储 WebSocket 会话
     * Key: sessionId, Value: WebSocketSession
     */
    private final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
    
    /**
     * 存储聊天历史
     * Key: sessionId, Value: 消息列表
     */
    private final ConcurrentHashMap<String, List<String>> chatHistory = new ConcurrentHashMap<>();
    
    /**
     * 添加会话
     */
    public void addSession(String sessionId, WebSocketSession session) {
        sessions.put(sessionId, session);
        chatHistory.putIfAbsent(sessionId, new CopyOnWriteArrayList<>());
        log.info("✅ Session added - SessionId: {}, Total sessions: {}", 
                sessionId, sessions.size());
    }
    
    /**
     * 移除会话
     */
    public void removeSession(String sessionId) {
        sessions.remove(sessionId);
        // 保留聊天历史一段时间，可以根据需要定期清理
        // chatHistory.remove(sessionId);
        log.info("❌ Session removed - SessionId: {}, Remaining sessions: {}", 
                sessionId, sessions.size());
    }
    
    /**
     * 获取会话
     */
    public WebSocketSession getSession(String sessionId) {
        return sessions.get(sessionId);
    }
    
    /**
     * 检查会话是否存在
     */
    public boolean hasSession(String sessionId) {
        return sessions.containsKey(sessionId);
    }
    
    /**
     * 获取会话数量
     */
    public int getSessionCount() {
        return sessions.size();
    }
    
    /**
     * 添加聊天消息
     */
    public void addMessage(String sessionId, String message) {
        chatHistory.computeIfAbsent(sessionId, k -> new CopyOnWriteArrayList<>()).add(message);
        log.debug("💬 Message added - SessionId: {}, Total messages: {}", 
                sessionId, chatHistory.get(sessionId).size());
    }
    
    /**
     * 获取聊天历史
     */
    public List<String> getHistory(String sessionId) {
        return chatHistory.getOrDefault(sessionId, new ArrayList<>());
    }
    
    /**
     * 获取最近的聊天历史
     */
    public List<String> getRecentHistory(String sessionId, int limit) {
        List<String> history = getHistory(sessionId);
        int size = history.size();
        if (size <= limit) {
            return new ArrayList<>(history);
        }
        return new ArrayList<>(history.subList(size - limit, size));
    }
    
    /**
     * 清空聊天历史
     */
    public void clearHistory(String sessionId) {
        chatHistory.remove(sessionId);
        log.info("🗑️ History cleared - SessionId: {}", sessionId);
    }
    
    /**
     * 获取所有活跃的会话ID
     */
    public Set<String> getAllSessionIds() {
        return new HashSet<>(sessions.keySet());
    }
    
    /**
     * 清理过期会话（定时任务）
     */
    public void cleanExpiredSessions() {
        sessions.forEach((sessionId, session) -> {
            if (!session.isOpen()) {
                removeSession(sessionId);
            }
        });
        log.info("🧹 Cleaned expired sessions, Remaining: {}", sessions.size());
    }
}
